package com.terra.ns.imp.common.util.http

import cn.hutool.core.net.NetUtil
import jakarta.servlet.http.HttpServletRequest

object IpUtils {

//    fun gerRequestIp(request: HttpServletRequest): String {
//        var ip = ""
//        var ipAddresses: String? = request.getHeader("X-Forwarded-For")
//        val unknown = "unknown"
//        if (ipAddresses.isNullOrBlank() || unknown.equals(ipAddresses, ignoreCase = true)) {
//            ipAddresses = request.getHeader("Proxy-Client-IP")
//        }
//        if (ipAddresses.isNullOrBlank() || unknown.equals(ipAddresses, ignoreCase = true)) {
//            ipAddresses = request.getHeader("WL-Proxy-Client-IP")
//        }
//        if (ipAddresses.isNullOrBlank() || unknown.equals(ipAddresses, ignoreCase = true)) {
//            ipAddresses = request.getHeader("HTTP_CLIENT_IP")
//        }
//        if (ipAddresses.isNullOrBlank() || unknown.equals(ipAddresses, ignoreCase = true)) {
//            ipAddresses = request.getHeader("X-Real-IP")
//        }
//        if (!ipAddresses.isNullOrEmpty()) {
//            ip = ipAddresses.split(",")[0]
//        }
//        if (ip.isEmpty() || unknown.equals(ipAddresses, ignoreCase = true)) {
//            ip = request.remoteAddr
//        }
//        return ip
//    }

    fun getRequestIp(request: HttpServletRequest, vararg headerNames: String): String {
        val baseHeaders = listOf(
            "X-Forwarded-For",
            "X-Real-IP",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP",
            "HTTP_X_FORWARDED_FOR"
        )
        val headers = if (headerNames.isNotEmpty()) {
            headerNames.asList().plus(baseHeaders)
        } else baseHeaders
        var ip : String?
        headers.forEach {
            ip = request.getHeader(it)
            if (!NetUtil.isUnknown(ip)) {
                return NetUtil.getMultistageReverseProxyIp(ip)
            }
        }
        ip = NetUtil.getMultistageReverseProxyIp(request.remoteAddr)
        if("0:0:0:0:0:0:0:1" == ip) {
            ip ="127.0.0.1"
        }
        return ip ?: ""
    }
}